#include <mqueue.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/signal.h>
#include <iostream>
using namespace std;

mqd_t mqd;
void* buff;
struct mq_attr attr;
struct sigevent sigev;

static void sig_usr1(int);

int main(int argc, char** argv)
{
    if(argc != 2){
        cout<< ("usage: nqnotifysig1 <name>");
        exit(-1);
    }
    mqd = mq_open(argv[1], O_RDONLY);
    mq_getattr(mqd, &attr);
    buff = malloc(attr.mq_msgsize);
    
    if(SIG_ERR == signal(SIGUSR1, sig_usr1)){
        cout << "SIG_ERR: " << strerror(errno) << endl;
        exit(-1);
    }
    cout << "SIGEV_SIGNAL = " << SIGEV_SIGNAL << endl;
    cout << "SIGUSR1      = " << SIGUSR1 << endl;
    
    sigev.sigev_notify = SIGEV_SIGNAL;
    sigev.sigev_signo = SIGUSR1;

    cout << "sigev.sigev_signo = " << sigev.sigev_signo << endl;
    
    if(mq_notify(mqd, &sigev) == -1){
        cout << "Error: " << strerror(errno) << endl;
        return -1;
    }
    
    for( ; ;)
        pause();
    exit(0);
}
static void sig_usr1(int signo)
{
    printf("here?");
    ssize_t n;
    mq_notify(mqd, &sigev);
    n = mq_receive(mqd, (char*)buff, attr.mq_msgsize, NULL);
    printf("SIGUSR1 received, read %ld bytes\n", (long) n);
    return ;
}
